from PySide6.QtWidgets import QComboBox, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QFrame
from PySide6.QtCore import Qt, QEvent, Signal

class CategoryTreeCombo(QComboBox):
    selectedChanged = Signal(int)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.category_tree = {}  # 存储分类树数据
        self.selected_id = None  # 存储选中的分类ID
    
    def setup_ui(self):
        # 设置样式
        self.setObjectName("categoryTreeCombo")
        
        # 创建树形控件
        self.tree = QTreeWidget()
        self.tree.setHeaderHidden(True)
        self.tree.setObjectName("categoryTree")
        
        # 创建弹出窗口
        self.popup = QFrame()
        self.popup.setWindowFlags(Qt.Popup | Qt.FramelessWindowHint | Qt.NoDropShadowWindowHint)
        self.popup.setObjectName("categoryTreePopup")
        
        # 设置弹出窗口布局
        popup_layout = QVBoxLayout(self.popup)
        popup_layout.setContentsMargins(0, 0, 0, 0)
        popup_layout.addWidget(self.tree)
        
        # 连接信号
        self.tree.itemClicked.connect(self.on_item_selected)
        
        # 重写事件过滤器
        self.installEventFilter(self)
    
    def eventFilter(self, obj, event):
        if obj == self and event.type() == QEvent.MouseButtonPress:
            if event.button() == Qt.LeftButton:
                self.show_popup()
                return True
        return super().eventFilter(obj, event)
    
    def show_popup(self):
        """显示弹出窗口"""
        # 计算弹出窗口位置
        rect = self.rect()
        pos = self.mapToGlobal(rect.bottomLeft())
        
        # 设置弹出窗口大小
        self.popup.setFixedWidth(self.width())
        self.popup.setFixedHeight(300)  # 设置最大高度
        
        # 显示弹出窗口
        self.popup.move(pos)
        self.popup.show()
        self.popup.raise_()
    
    def set_categories(self, category_tree):
        """设置分类数据
        Args:
            category_tree: parse_category_tree 返回的分类树数据
        """
        self.category_tree = category_tree
        self.tree.clear()
        self.clear()  # 清空下拉列表
        
        # 构建树形结构
        root_items = {}  # 存储所有节点，用于构建父子关系
        for category_id, category in category_tree.items():
            item = QTreeWidgetItem([category['name']])
            item.setData(0, Qt.UserRole, category_id)  # 存储分类ID
            root_items[category_id] = item
            
            if category['parent_id'] is None:
                # 顶级分类
                self.tree.addTopLevelItem(item)
            else:
                # 子分类
                parent_item = root_items.get(category['parent_id'])
                if parent_item:
                    parent_item.addChild(item)
        
        self.tree.expandAll()
        
        # 默认选中第一个分类
        if self.tree.topLevelItemCount() > 0:
            first_item = self.tree.topLevelItem(0)
            self.set_item_selected(first_item)

    def on_item_selected(self, item):
        self.set_item_selected(item)
        self.selectedChanged.emit(item.data(0, Qt.UserRole))
    
    def set_item_selected(self, item):
        """处理分类选择"""
        # 获取选中的分类ID
        self.selected_id = item.data(0, Qt.UserRole)
        
        # 构建完整路径
        path = []
        current = item
        while current:
            path.insert(0, current.text(0))
            current = current.parent()
        
        # 设置显示文本
        full_path = " > ".join(path)
        
        # 清空并添加新选项
        self.clear()
        self.addItem(full_path)
        self.setCurrentIndex(0)  # 选中新添加的项
        
        self.popup.hide()
    
    def get_selected_id(self):
        """获取当前选中的分类ID"""
        return self.selected_id
    
    def get_current_path(self):
        """获取当前选择的完整路径"""
        return self.currentText()
    
    def set_selected_id(self, category_id):
        """设置选中的分类ID"""
        if category_id is None:
            # 如果没有指定ID，选中第一个分类
            if self.tree.topLevelItemCount() > 0:
                first_item = self.tree.topLevelItem(0)
                self.set_item_selected(first_item)
            return
        
        # 查找对应的树节点
        def find_item(item, target_id):
            if item.data(0, Qt.UserRole) == target_id:
                return item
            for i in range(item.childCount()):
                found = find_item(item.child(i), target_id)
                if found:
                    return found
            return None
        
        # 在所有顶级节点中查找
        for i in range(self.tree.topLevelItemCount()):
            item = find_item(self.tree.topLevelItem(i), category_id)
            if item:
                self.selected_id = category_id
                self.set_item_selected(item)
                return
        
        # 如果没找到，选中第一个分类
        if self.tree.topLevelItemCount() > 0:
            first_item = self.tree.topLevelItem(0)
            self.set_item_selected(first_item) 
